package listener;

import java.util.Date;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import model.beans.ShoppingCartBean;

import util.ProjectConstants;
import util.TimeCounter;

/**
 * Application Lifecycle Listener implementation class ShoppingCartListener
 * 
 */
@WebListener
public class ShoppingCartListener implements HttpSessionAttributeListener
{

	/**
	 * Default constructor.
	 */
	public ShoppingCartListener()
	{
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
	 */
	public void attributeRemoved(HttpSessionBindingEvent arg0)
	{
		// get session
		HttpSession session = arg0.getSession();
		try
		{
			// get session attribute names
			String shoppingCart = ProjectConstants.PARAMMYCART;
			String checkoutTimes = ProjectConstants.PARAMCHECKOUTTIMES;
			// calculate the time when the shoppingCart attribute is removed
			if (shoppingCart.equals(arg0.getName()))
			{
				// get the time now
				Date now = new Date();
				long lastCheckoutTime; // define lastCheckout Time for the same
										// client in the same session
				// retrieve last adding time
				if (session.getAttribute(ProjectConstants.LASTCHECKOUTTIME) == null)
				{
					lastCheckoutTime = session.getCreationTime();
					// set the current time to the lastAddtime attribute in
					// session
				}
				else
				{
					lastCheckoutTime = (Long) session.getAttribute(ProjectConstants.LASTCHECKOUTTIME);
				}
				
				// calculate the time difference between the fresh visit and checkout time 
				// if 2 checkout happened in the same session. the time difference of the second time is from last check out to the 2nd time checkout
				long timeDiff = now.getTime() - lastCheckoutTime;
			
				// start to update the counter
				TimeCounter counter = (TimeCounter) session.getServletContext().getAttribute(ProjectConstants.AVGCHECKOUT);				
				
				counter.increaseTime(timeDiff);
				counter.increaseClicks();
					
				// set the lastCheckoutTime in session
				session.setAttribute(ProjectConstants.LASTCHECKOUTTIME, now.getTime());
				
				
////				System.out.println("new total check out time : " + counter.getTime()  + "  clicks "+ counter.getClicks());				
//
//	
//				long eslapedTime = now.getTime() - session.getCreationTime();
//				// get the check out times value
//				int frequency = (Integer) session.getAttribute(checkoutTimes);
//				long avgCheckout = eslapedTime / frequency / 1000;
//				// set avg checkout time in session
////				session.setAttribute(ProjectConstants.AVGCHECKOUT, avgCheckout);
//				 System.out.println("It takes you " + eslapedTime/1000 +" seconds to check out "+ frequency +" times!");
			}
		}
		catch (IllegalStateException e)
		{
			e.printStackTrace();
			System.out.println("session is invalidated!");
		}
	}

	/**
	 * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
	 */
	public void attributeReplaced(HttpSessionBindingEvent arg0)
	{
		// retrieve session
		HttpSession session = arg0.getSession();

		// retrieve shoppingcart session attribute name
		String shoppingCart = ProjectConstants.PARAMMYCART;

		// calculate when shoppingCart attribute changes
		if (shoppingCart.equals(arg0.getName()))
		{
			// get the time now
			Date now = new Date();
			long lastAddTime; // define last add item time
			// retrieve last adding time
			if (session.getAttribute(ProjectConstants.LastAddTime) == null)
			{
			System.out.println("lastAddTime  is null" );	
				lastAddTime = session.getCreationTime();
				// set the current time to the lastAddtime attribute in session
			}
			else
			{
				lastAddTime = (Long) session.getAttribute(ProjectConstants.LastAddTime);
			}

			// calculate the time difference between the time of last adding
			// item and that of this time
			long timeDiff = now.getTime() - lastAddTime;

			// retrieve the counter from application
			TimeCounter counter = (TimeCounter) session.getServletContext()
					.getAttribute(ProjectConstants.AVGADDTIME);
			// increase the time
			counter.increaseTime(timeDiff);
			// increase the clicks
			counter.increaseClicks();

			// set the lastAddTime to session attribute
			session.setAttribute(ProjectConstants.LastAddTime, now.getTime());

			
			
			
//			long eslapedTime = now.getTime() - arg0.getSession().getCreationTime();            
//            ShoppingCartBean sc = (ShoppingCartBean) arg0.getSession().getAttribute(shoppingCart);
//            long averageTime =  (eslapedTime / sc.getNumOfItems()) /1000 ;
//            
//            // set the attribute in the session
////            arg0.getSession().setAttribute("cAvgAdd", averageTime);
//            
//            System.out.println("time diff: " + timeDiff + "; total time: " + counter.getTime() + " total #: " + counter.getClicks() + " avgTime :" + counter.getAvgTime());
//            System.out.println("It takes you " + eslapedTime +" seconds to add " + sc.getNumOfItems() + " items to the cart! The avg time is " + averageTime
//                            + " seconds !");
		}
	}

	/**
	 * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
	 */
	public void attributeAdded(HttpSessionBindingEvent arg0)
	{
		// TODO Auto-generated method stub
	}

}
